/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.ntb.common;

import com.ntb.entities.Users;
import com.ntb.models.PermissionsDAO;
import com.ntb.models.UsersDAO;
import com.ntb.models.impl.PermissionsDAOImpl;
import com.ntb.models.impl.UsersDAOImpl;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

/**
 *
 * SecuredAction - common action: used to manage user states: logged or not logged
 * 
 * @author Thinh Hung
 */
public abstract class SecuredAction extends Action {

    protected Users currentUser = null;
    private List<String> userPermissions;
    protected String module = null;

    @Override
    public final ActionForward execute(ActionMapping mapping,
            ActionForm form,
            HttpServletRequest request,
            HttpServletResponse response) {
        ActionForward forward = null;

        Cookie[] cookies = request.getCookies();

        int useridCookie = -1;
        String remembercodeCookie = null;
        // find value of cookies
        if (cookies != null) {
            for (int i = 0; i < cookies.length; i++) {
                if ("userid".equals(cookies[i].getName())) {
                    useridCookie = Integer.parseInt(cookies[i].getValue());
                }
                if ("remembercode".equals(cookies[i].getName())) {
                    remembercodeCookie = cookies[i].getValue();
                }
            }
        }

        UsersDAO usersDao = new UsersDAOImpl();

        // check remember me
        if (useridCookie != -1 && !remembercodeCookie.equals(null)) {
            int userId = usersDao.checkRememberCode(
                    new StringUtil().generateMD5(remembercodeCookie),
                    useridCookie);
            if (userId != -1) {
                request.getSession(true).setAttribute("userid", userId);
            }
        }

        // Set the current user by user id session
        if (request.getSession().getAttribute("userid") != null) {
            this.currentUser = usersDao.getRow(
                    Integer.parseInt(String.valueOf(request.getSession().getAttribute("userid"))));
        } else {
            currentUser = null;
            userPermissions = null;
        }

        // If the current user is null, then delete all session and redirect to login page
        if (this.currentUser != null) {
            // Set attributes: used to access at jsp files
            request.setAttribute("currentUser", this.currentUser);

            forward = ntbExecute(mapping, form, request, response);

            /**
             * Check permisson
             */
            PermissionsDAO permissionsDao = new PermissionsDAOImpl();
            this.userPermissions = permissionsDao.getPermissionsList(this.currentUser.getGroupID());

            List<String> permissions = permissionsDao.getAllPermissions();

            // Module
            module = request.getServletPath();
            module = module.substring("/admin/".length(), module.indexOf(".do"));
            if (module.indexOf("Listing") > 0) {
                module = module.substring(0, module.indexOf("Listing"));
            }

            if (permissions.contains(module)) {
                if (!this.userPermissions.contains(module)) {
                    forward = mapping.findForward("noPermission");
                }
            }

            ArrayList menuList = getMenu(permissionsDao, userPermissions);
            request.setAttribute("menuList", menuList);
            System.out.println("This module is " + module);

        } else {
            request.getSession().invalidate();
            forward = mapping.findForward("login");
        }

        return forward;
    }

    public abstract ActionForward ntbExecute(ActionMapping mapping,
            ActionForm form,
            HttpServletRequest request,
            HttpServletResponse response);

    private ArrayList getMenu(PermissionsDAO dao, List<String> permissions) {
        ArrayList menuList = new ArrayList();

        Map landMenu = new HashMap();
        landMenu.put("name", "Lands");
        List landChilds = new ArrayList();

        Map buildingMenu = new HashMap();
        buildingMenu.put("name", "Buildings");
        List buildingChilds = new ArrayList();

        Map saleMenu = new HashMap();
        saleMenu.put("name", "Sales");
        List saleChilds = new ArrayList();

        Map userMenu = new HashMap();
        userMenu.put("name", "Users");
        List userChilds = new ArrayList();

        Map contactMenu = new HashMap();
        contactMenu.put("name", "Contacts");
        List contactChilds = new ArrayList();

        Iterator permissionsTable = dao.getPermissionsTable();

        for (Iterator<String[]> it = permissionsTable; it.hasNext();) {
            String [] item = it.next();

            String mod = item[0];
            String menu = item[2];
            
            if (permissions.contains(item[0])) {
                if("land".equals(menu)) {
                    landChilds.add(item);
                    if (this.module.equals(mod)) {
                        landMenu.put("active", "active");
                    }
                } else if ("building".equals(menu)) {
                    buildingChilds.add(item);
                    if (this.module.equals(mod)) {
                        buildingMenu.put("active", "active");
                    }
                } else if ("sale".equals(menu)) {
                    saleChilds.add(item);
                    if (this.module.equals(mod)) {
                        saleMenu.put("active", "active");
                    }
                } else if ("user".equals(menu)) {
                    userChilds.add(item);
                    if (this.module.equals(mod)) {
                        userMenu.put("active", "active");
                    }
                } else if ("contact".equals(menu)) {
                    contactChilds.add(item);
                    if (this.module.equals(mod)) {
                        contactMenu.put("active", "active");
                    }
                }
            }
        }
        landMenu.put("childs", landChilds);
        buildingMenu.put("childs", buildingChilds);
        saleMenu.put("childs", saleChilds);
        userMenu.put("childs", userChilds);
        contactMenu.put("childs", contactChilds);
        
        menuList.add(landMenu);
        menuList.add(buildingMenu);
        menuList.add(saleMenu);
        menuList.add(userMenu);
        menuList.add(contactMenu);

        return menuList;
    }
}
